package com.xtianzhuang.www.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

/**
 * 
 * @author xtian.zhuang
 *
 */
@Aspect
@Component
public class LogAspect {
	private static Logger logger = LoggerFactory.getLogger(LogAspect.class);

	@Pointcut("@annotation(com.xtianzhuang.www.annotation.Log)")
	public void logAspect() {

	}

	// @Before("logAspect()")
	// public void logBofore(JoinPoint joinPoint) {
	// Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
	// if (method != null) {
	// Log log = method.getAnnotation(Log.class);
	// logger.debug("------------------------" + method.getName() + ": " + log.type()
	// + "------------------------ start");
	// String msg = "";
	// Class<?>[] params = method.getParameterTypes();
	// Object[] args = joinPoint.getArgs();
	// for (int i = 0; i < args.length; i++) {
	// msg += params[i].getName() + "[param" + (i + 1) + "]" + "="
	// + new JSONSerializer().deepSerialize(args[i]) + "\n";
	// }
	// logger.debug(msg);
	//
	// }
	// }
	//
	// @After("logAspect()")
	// public void logAfter(JoinPoint joinPoint) {
	// Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
	// if (method != null) {
	// Log log = method.getAnnotation(Log.class);
	// logger.debug(
	// "------------------------" + method.getName() + ": " + log.type() + "------------------------ end");
	// }
	// }

	@Around("logAspect()")
	public Object doSurround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		Object[] objects = proceedingJoinPoint.getArgs();
		String name = proceedingJoinPoint.getSignature().getName();
		logger.info("------------------------" + name + "------------------------ start");
		long startTime = System.currentTimeMillis();
		String msg = "";
		for (int i = 0; i < objects.length; i++) {
			try {
				msg += "[param" + (i + 1) + "]" + "=" + JSON.toJSONString(objects[i]) + "\n";
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
		logger.info("input args \n" + msg);
		Object result = proceedingJoinPoint.proceed();
		logger.info("output args: \n{}\n", JSON.toJSONString(result));
		logger.info("------------------------" + name + "------------------------ end");

		logger.info("execute time: {}", System.currentTimeMillis() - startTime);

		return result;
	}

}
